<?php

namespace App\Dao;

use App\Actions\MessageAction;
use App\Model\AnchorEvaluate;
use App\Model\Gift;
use App\Model\SendGiftItem;
use App\Model\User;
use App\Services\PushMessageService;
use App\Services\Queue\QueueService;
use App\Utils\MemcacheClient;
use Hyperf\Collection\Collection;
use Hyperf\Context\ApplicationContext;
use Hyperf\Context\Context;
use Hyperf\Database\Model\Builder;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use function Hyperf\Translation\trans;

class GiftDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    /**
     * 用户送出、收到的礼物及数量
     * @param $uid
     * @param int $type 1送出的礼物 2收到的礼物
     * @param int $size
     * @return mixed[]
     */
    public function getGiftByUid($uid, int $type = 1, int $size = 0)
    {
        $language = Context::get('language', 'en');
        // $filed = $type == 1 ? "tb_send_gift_item.send_uid" : "tb_send_gift_item.get_uid";
        $query = SendGiftItem::query()->leftJoin('tb_gift', 'tb_send_gift_item.gid', 'tb_gift.id')
            // ->where($filed, $uid)
            ->when($type == 1, function (Builder $query) use ($uid) {
                $query->where('tb_send_gift_item.send_uid', $uid);
            }, function (Builder $query) use ($uid) {
                $query->where('tb_send_gift_item.get_uid', $uid);
            })
            ->groupBy('tb_send_gift_item.gid')
            ->orderBy('num', 'desc')
            ->when($size, function (Builder $query) use ($size) {
                $query->limit($size);
            });
        if ($language == 'zh-hk') {
            // $sql = "select b.hk_name as name,b.img,sum(a.num)as num from {$this->tableS} a inner join {$this->table} b ON a.gid = b.id  where {$filed} = ? group by a.gid order by num desc" . $limit;
            $data = $query->selectRaw('tb_gift.hk_name as name, tb_gift.img, sum(tb_send_gift_item.num) as num')->get();
        } elseif ($language == 'zh-cn') {
            // $sql = "select b.name as name,b.img,sum(a.num)as num from {$this->tableS} a inner join {$this->table} b ON a.gid = b.id  where {$filed} = ? group by a.gid order by num desc" . $limit;
            $data = $query->selectRaw('tb_gift.name as name, tb_gift.img, sum(tb_send_gift_item.num) as num')->get();
        } else {
            // $sql = "select b.en_name as name,b.img,sum(a.num)as num from {$this->tableS} a inner join {$this->table} b ON a.gid = b.id  where {$filed} = ? group by a.gid order by num desc" . $limit;
            $data = $query->selectRaw('tb_gift.en_name as name, tb_gift.img, sum(tb_send_gift_item.num) as num')->get();
        }

        return $data->toArray();
    }


    /**
     * Note - 获取首页礼物飘窗数据列表
     * DateTime 2024/8/13 16:40
     * User Admin
     * @param $end_time
     * @return mixed
     */
    public function getGiftShowList($end_time)
    {
        $send_gift_count = SettingDao::getInstance()->getOne('send_gift_count');
        $field = 's.send_uid uid,
        2 notice_type,
        su.nickname nickname,
        su.head_image head_image,
        su.sex,
        gu.nickname user_nickname,
        gu.head_image user_head_image,
        gu.sex user_sex,
        s.get_uid user_id,
        g.img,
        g.name gift_name,
        g.en_name gift_en_name,
        g.hk_name gift_hk_name,
        s.num,case when s.cost<999 then 3 when s.cost>=999 and s.cost<2999 then 10 when s.cost>=2999 and s.cost<5000 then 20 when s.cost>=5000 then 30 end as wait,
        1 sub_type,
        s.send_time end_time';
        return SendGiftItem::query()->from('tb_send_gift_item AS s')
            ->leftJoin('tb_gift AS g', 's.gid', 'g.id')
            ->leftJoin('tb_user AS su', 's.send_uid', 'su.id')
            ->leftJoin('tb_user AS gu', 's.get_uid', 'gu.id')
            ->selectRaw($field)
            ->where('s.cost', '>=', $send_gift_count)->where('su.sex', 1)
            // ->where('s.send_time', '<=', $end_time)
            ->orderBy('s.send_time', 'desc')
            ->limit(20)
            ->get()->toArray();
    }


    /**
     * Note - 发送免费礼物
     * DateTime 2024/8/14 16:33
     * User Admin
     * @param $uid
     * @param $to_uid
     * @param $gift_id
     * @param $language
     */
    public function sendFreeGift($uid, $to_uid, $gift_id, $language)
    {
        $userInfo = UserDao::getInstance()->findUserInfoCache($uid);
        $giftInfo = $this->getGiftCache($gift_id);

        $insertData = array();
        $insertData['uid'] = (int)$uid;
        $insertData['receive_uid'] = (int)$to_uid;
        $insertData['content'] = '';
        $insertData['ctime'] = getMillisecond() - 1000;
        $insertData['chat_type'] = 11;  //通话过程中用户送礼
        $insertData['content_type'] = 6; //送礼动画，仅在chat_type=11才有
        $insertData['from'] = 1;
        $insertData['version_code'] = $userInfo['version_code'];
        $insertData['channel_number'] = $userInfo['channel'];

        $gift_amount = 0;
        $gift_data = array(
            'call_id' => 0,
            'gid' => $gift_id,
            'name' => $language == 'zh-cn' ? $giftInfo['name'] : ($language == 'zh-hk' ? $giftInfo['hk_name'] : $giftInfo['en_name']),
            'unit_profit' => 0,
            'img' => $giftInfo['img'],
            'num' => 1,
            'effect_url' => $giftInfo['effect_url'],
            'gift_amount' => $gift_amount,
            'gift_type' => 1,        // 1搭讪礼物
        );
        $insertData['gift_data'] = $gift_data;
        // $insertData['look'] = 0;  //是否已读
        // $insertData['date'] = date("Y-m-d");

        $format = (new MessageAction())->formatUserInfo($userInfo);
        unset($format['from'], $format['version_code'], $format['channel']);

        $insertData['user_info'] = $format;
        // $toInfo = (new UserModel())->find("id,nickname,head_image", "id=?", [$to_uid]);
        $toInfo = User::query()->find($to_uid, ['id', 'nickname', 'head_image']);
        $toInfo = modelToArray($toInfo);
        $insertData['receiver'] = $toInfo;
        $insertData['sync_sender'] = 1;
        // $insertData['sort_type'] = 0;
        $insertData['msg_type'] = 2;
        $insertData['closeness'] = ClosenessDao::read($to_uid, $uid);
        $msg = json_encode(array('event' => 'user_conn', 'client_uid' => $uid, 'msg' => [$insertData], 'desc' => 'success'), JSON_UNESCAPED_UNICODE);
        // (new WyyClient())->putAttachMsgQueue($uid, $to_uid, $msg);
        // (new WyyClient())->putCustomMsgQueue($uid, $to_uid, $msg);
        PushMessageService::putYunXinCustomMsgQueue($uid, $to_uid, $msg);
    }


    /**
     * Note -
     * DateTime 2024/8/14 16:38
     * User Admin
     * @param $gid
     * @return mixed
     */
    public function getGiftCache($gid, $cache = true)
    {
        $giftInfo = MemcacheClient::getInstance()->get('giftInfo_' . $gid);
        if ($giftInfo === false || !$cache) {
            // $sql = "select * from {$this->table} where id = ?";
            // $pd = $this->createCommand($sql);
            // $pd->execute(array($gid));
            // $giftInfo = $pd->fetch(PDO::FETCH_ASSOC);
            $giftInfo = Gift::query()->find($gid);
            $giftInfo = modelToArray($giftInfo);
            if ($cache) {
                MemcacheClient::getInstance()->set('giftInfo_' . $gid, $giftInfo, 300);
            }
        }

        return $giftInfo;
    }


    /**
     * Note - 获取所有礼物
     * DateTime 2024/8/16 18:32
     * User Admin
     * @return mixed
     */
    public function getAllGift()
    {
        $cache = MemcacheClient::getInstance()->get('all_usable_gift');
        if ($cache === false) {
            $cache = Gift::query()->where('status', 0)->orderByRaw('orders asc,price asc')->get()->toArray();
            MemcacheClient::getInstance()->set('all_usable_gift', $cache, 60);
        }
        return $cache;
    }


    /**
     * Note - 根据 call_id 统计用户消费金币
     * DateTime 2024/8/19 14:43
     * User Admin
     * @param $uid
     * @param $call_id
     * @return int
     */
    public function getGiftCost($uid, $call_id = 0)
    {
        // $sql = "select sum(cost) costs from {$this->tableS} where send_uid = ? and call_id = ?";
        // $pd = $this->createCommand($sql);
        // $pd->execute(array($uid, $call_id));
        // $rs = $pd->fetch(PDO::FETCH_ASSOC);
        // return (int)$rs['costs'];
        return SendGiftItem::query()->where('send_uid', $uid)->where('call_id', $call_id)->sum('cost');
    }

}